package com.lagou.task.servlet;

import com.lagou.task.entity.Student;
import com.lagou.task.entity.SysClass;
import com.lagou.task.service.ClassService;
import com.lagou.task.service.StudentService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ClassAddServlet",urlPatterns = "/classAdd")
public class ClassAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码格式
        request.setCharacterEncoding("UTF-8");
        // 获取参数并创建对象
        String className = request.getParameter("className");
        String classGrade = request.getParameter("grade");
        String classTeacher = request.getParameter("teacher");
        String classSlogan = request.getParameter("slogan");
        String classNumber = request.getParameter("number");

        SysClass sysClass = new SysClass(className,classGrade,classTeacher,classSlogan,Integer.parseInt(classNumber));

        // 添加班级信息服务
        ClassService classService = new ClassService();
        // 计算班级学生人数
        //classService.claculateClassNumber(sysClass);
        int i = classService.addClassService(sysClass);
        if (i == 1){
            //response.sendRedirect("list");
            request.setAttribute("addSuccess","addSuccess");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("class");
            requestDispatcher.forward(request, response);
            if (request.getAttribute("addError") != null){
                request.removeAttribute("addError");
            }
        }else {
            request.setAttribute("addError","addError");
            // 实现服务器跳转  共享request和response对象
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("class");
            requestDispatcher.forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
